package com.qdh.demo6;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;

import java.io.IOException;


public class GoodsCountJob {
    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
      /*  if (args.length!=2) {
            System.out.println("请提供合理参数");
            System.exit(0);
        }*/
        // 1. 初始化配置
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS","hdfs://hadoop11:8020");
        //2. 创建job
        Job job = Job.getInstance(conf);
        job.setJarByClass(GoodsCountJob.class);

        //3. 设置输入格式化工具和输出格式化
        job.setInputFormatClass(TextInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);

        //4. 设置输入路径和输出路径
        //TextInputFormat.addInputPath(job,new Path("/wc2.txt"));
        //TextOutputFormat.setOutputPath(job,new Path("/out"));

        TextInputFormat.addInputPath(job,new Path("/mapreduce/demo9"));
        TextOutputFormat.setOutputPath(job,new Path("/mapreduce/demo9/out"));

        //5. 设置mapper和reducer
        job.setMapperClass(GoodsCountMapper.class);
        job.setReducerClass(GoodsCountReducer.class);

        // 6. 设置mapper的kv类型和reducer的kv类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        //设置reduceTask个数：并行执行，提高效率
        job.setNumReduceTasks(2);

        // 7. 启动job
        boolean b = job.waitForCompletion(true);
        System.out.println(b?"成功":"失败");
    }
    //局部计算
    static  class GoodsCountMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {

            String[] split = value.toString().split("\t");
            context.write(new Text(split[split.length-2]), new IntWritable(1));
        }
    }
    //汇总计算
    static class GoodsCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            // value 10001 [1,1,1,1,1,1,1]
            int sum = 0;
            for (IntWritable value : values) {
                sum += value.get();
            }
            context.write(key, new IntWritable(sum));
        }
    }
}
